package service

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"project1/util"
	"project1/validate"
	"time"

	"github.com/tidwall/gjson"
)

var (
	Appoint_N = base64.StdEncoding.EncodeToString([]byte("coinglass" + "/api/home/v2/coinMarkets" + "coinglass"))[:16]
)

type EncryptionService struct{}

// 搜索指定币
func (e *EncryptionService) Coinglass_Appoint(body validate.CoinName) (any, error) {
	// 获取当前时间的十三位数时间戳
	currentTime := time.Now().UnixNano() / 1000000
	cacheTs := fmt.Sprintf("%d", currentTime)
	// 获取user
	user, err := getUser("https://capi.coinglass.com/api/futures/home/statistics", cacheTs)
	if err != nil {
		return "", errors.New("获取user参数错误")
	}
	users := user.Header.Get("User")
	fmt.Printf("user: %s\n", users)

	// 解密user获取解密返回参数的秘钥
	keyStr, err := encryption(users, Appoint_N)
	if err != nil {
		return "", errors.New("解密users参数错误")
	}

	// 获取encData
	url := fmt.Sprintf("https://capi.coinglass.com/api/home/v2/coinMarkets?sort=&order=&keyword=%s&pageNum=%d&pageSize=%d&ex=all", body.CoinName, body.Page, body.PageSize)
	encDataResponse, err := getUser(url, cacheTs)
	if err != nil {
		return "", errors.New("搜索币失败")
	}
	// 读取响应内容
	Data, err := ioutil.ReadAll(encDataResponse.Body)
	if err != nil {
		return "", errors.New("读取响应体时出错:" + err.Error())
	}
	// 解析出响应内容中 data 字段内容
	encData := gjson.Get(string(Data), "data").String()
	if encData == "" {
		return "", errors.New("搜索币失败")
	}

	// 解密响应内容
	encryptionData, err := encryption(encData, keyStr)
	if err != nil {
		fmt.Println("解密失败:", err)
		return "", errors.New("解密失败:" + err.Error())
	}

	// 关闭响应体
	defer encDataResponse.Body.Close()
	defer user.Body.Close()

	// 处理返回内容
	// 解析出响应内容中 list 字段内容
	encryptionData = gjson.Get(encryptionData, "list").String()
	if encData == "" {
		return "", errors.New("搜索币失败")
	}

	var coinData []validate.CoinData
	err = json.Unmarshal([]byte(encryptionData), &coinData)
	if err != nil {
		return nil, err
	}

	return map[string]any{
		"list":     coinData,
		"page":     body.Page,
		"pageSize": body.PageSize,
		"count":    len(coinData),
	}, err
}

func getUser(url, cacheTs string) (*http.Response, error) {

	// 创建一个 HTTP GET 请求
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("创建请求失败:", err)
		return nil, errors.New("创建请求失败:" + err.Error())
	}

	// 设置请求头
	req.Header.Set("Cache-Ts", cacheTs)
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("发送请求失败:", err)
		return nil, errors.New("发送请求失败:" + err.Error())
	}
	return resp, nil
}

func encryption(encData, keyStr string) (string, error) {
	// 解析 Key
	key := []byte(keyStr)

	// base64 解码
	ciphertext, err := base64.StdEncoding.DecodeString(encData)
	if err != nil {
		fmt.Println("解码错误:", err)
		return "", errors.New("解码错误:" + err.Error())
	}

	// AES 解密
	decrypted, err := util.AESDecrypt(ciphertext, key)
	if err != nil {
		fmt.Println("解密错误:", err)
		return "", errors.New("解密错误:" + err.Error())
	}

	// 解压缩
	result, err := util.Decompress(decrypted)
	if err != nil {
		fmt.Println("解压缩错误:", err)
		return "", errors.New("解压缩错误:" + err.Error())
	}
	return string(result), nil
}
